package com.talis.service.impl.impl;

import com.talis.constant.MessageConstant;
import com.talis.entity.Dept;
import com.talis.exception.DeletionNotAllowedException;
import com.talis.mapper.DeptMapper;
import com.talis.mapper.EmpMapper;
import com.talis.service.impl.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    public void save(Dept dept) {
        //补全基础属性
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        //保存部门
        deptMapper.insert(dept);
    }
    public List<Dept> findAll() {
        return deptMapper.findAll();
    }
    public void deleteById(Integer id) {
        //判断当前部门是否能够删除--是否有员工？
        List<Integer> empIDs = empMapper.getEmpIDByDeptID(id);
        if(empIDs != null && empIDs.size() > 0){
            //有员工，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DEPT_BE_RELATED_BY_EMP);
        }

        deptMapper.deleteById(id);
    }

    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }
    public void update(Dept dept) {
        //补全基础属性
        dept.setUpdateTime(LocalDateTime.now());
        //保存部门
        deptMapper.update(dept);
    }
}
